# apps/cache_utils.py
from django.core.cache import caches

local_cache = caches['default']
redis_cache = caches['redis']


def tiered_caching(key, default_func, timeout=3600):
    # 1. 尝试获取本地缓存
    result = local_cache.get(key)
    if result is not None:
        return result

    # 2. 尝试获取Redis缓存
    result = redis_cache.get(key)
    if result is not None:
        # 回填本地缓存
        local_cache.set(key, result, min(300, timeout))
        return result

    # 3. 执行原始函数获取数据
    result = default_func()

    # 4. 设置两级缓存
    redis_cache.set(key, result, timeout)
    local_cache.set(key, result, min(300, timeout))

    return result
